package com.yanqu.road.server.gameplayer.module.activity.guagifts;

import com.yanqu.road.dao.impl.player.*;
import com.yanqu.road.entity.activity.guagifts.UserGuaData;
import com.yanqu.road.entity.activity.guagifts.UserGuaGiftData;
import com.yanqu.road.entity.activity.guagifts.UserGuaNobleRelationData;
import com.yanqu.road.entity.activity.guagifts.UserGuaRelationData;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.log.LogGuaGiftsReceiveBroadcast;
import com.yanqu.road.entity.log.LogGuaGiftsReceiveGift;
import com.yanqu.road.entity.log.LogGuaGiftsSendGift;
import com.yanqu.road.entity.player.PlayerState;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.relatives.RelativesInfo;
import com.yanqu.road.entity.servercenter.GameEditLimit;
import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.activity.GuaGiftsConfig.GuaGiftsConfig;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.pb.activity.GuaGiftsProto;
import com.yanqu.road.pb.activity.QixiProto;
import com.yanqu.road.pb.player.PlayerProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.PreReduceModule;
import com.yanqu.road.server.gameplayer.module.relatives.RelativesModule;
import com.yanqu.road.server.manger.ForbiddenMgr;
import com.yanqu.road.server.manger.ForbiddenWordMgr;
import com.yanqu.road.server.manger.GameEditLimitMgr;
import com.yanqu.road.server.manger.ServerLanguageMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.guagifts.GuaGiftsMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.relatives.RelativesMgr;
import com.yanqu.road.server.manger.system.CommonMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.protocol.*;
import com.yanqu.road.sync.message.SyncResponse;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.mina.util.ConcurrentHashSet;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

public class GuaGiftsModule extends GeneralModule {
    public GuaGiftsModule(GamePlayer player) {
        super(player);
    }

    private UserGuaData userData;
    private List<UserGuaGiftData> userNobleGiftList = new ArrayList<>();
    private List<UserGuaGiftData> needUpdateGiftList = new ArrayList<>();

    /**
     * 孤寡别人送礼信息,没有礼物
     */
    private List<UserGuaGiftData> userGuaGiftList = new ArrayList<>();
    private Map<Long, UserGuaRelationData> userRelationMap = new ConcurrentHashMap<>();
    private Map<Long, UserGuaNobleRelationData> userNobleRelationMap = new ConcurrentHashMap<>();
    /**
     * 缓存孤寡榜单值
     */
    private Map<Long, Integer> cacheTargetGuaTotalCountMap = new ConcurrentHashMap<>();
    /**
     * 缓存贵族榜单值
     */
    private Map<Long, Integer> cacheTargetNobleTotalCountMap = new ConcurrentHashMap<>();

    /**
     * 送出去等待返回处理的玩家
     */
    private Set<Long> waitSendGiftBackUserIdSet = new ConcurrentHashSet<>();

    @Override
    public boolean loadData() {
        if (GuaGiftsMgr.getConfig() == null) {
            return true;
        }
        UserGuaData tempUserData = new UserGuaDaoImpl().getUserGuaData(GuaGiftsMgr.getConfig().getActivityId(), player.getUserId());
        Map<Long, UserGuaRelationData> tempRelationDataMap = new UserGuaRelationDaoImpl().getUserGuaRelationData(GuaGiftsMgr.getConfig().getActivityId(), player.getUserId());
        Map<Long, UserGuaNobleRelationData> tempNobleRelationDataMap = new UserGuaNobleRelationDaoImpl().getUserGuaNobleRelationData(GuaGiftsMgr.getConfig().getActivityId(), player.getUserId());
        List<UserGuaGiftData> tempGiftList = new UserGuaGiftDaoImpl().getUserGuaGiftData(GuaGiftsMgr.getConfig().getActivityId(), player.getUserId());
        List<UserGuaGiftData> tempNobleGiftList = new ArrayList<>();
        List<UserGuaGiftData> tempGuaGiftList = new ArrayList<>();
        for (UserGuaGiftData userGiftData : tempGiftList) {
            if (userGiftData.getGiftType() == 1) {
                tempNobleGiftList.add(userGiftData);
            } else {
                tempGuaGiftList.add(userGiftData);
            }
        }

        while (tempGuaGiftList.size() > GuaGiftsMgr.getConfig().getGIFT_LIMIT()){
            tempGuaGiftList.remove(0);
        }

        userData = tempUserData;
        userRelationMap = tempRelationDataMap;
        userNobleRelationMap = tempNobleRelationDataMap;
        userNobleGiftList = tempNobleGiftList;
        userGuaGiftList = tempGuaGiftList;

        initUserData();
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        if (userData != null) {
            if (userData.isInsertOption()) {
                new UserGuaDaoImpl().add(userData);
            } else if (userData.isUpdateOption()) {
                new UserGuaDaoImpl().update(userData);
            }
        }

        List<UserGuaRelationData> relationDataList;
        synchronized (userRelationMap) {
            relationDataList = new ArrayList<>(userRelationMap.values());
        }

        for (UserGuaRelationData userGuaRelationData : relationDataList) {
            if (userGuaRelationData.isInsertOption()) {
                new UserGuaRelationDaoImpl().add(userGuaRelationData);
            } else if (userGuaRelationData.isUpdateOption()) {
                new UserGuaRelationDaoImpl().update(userGuaRelationData);
            }
        }

        List<UserGuaNobleRelationData> nobleRelationDataList;
        synchronized (userNobleRelationMap) {
            nobleRelationDataList = new ArrayList<>(userNobleRelationMap.values());
        }

        for (UserGuaNobleRelationData data : nobleRelationDataList) {
            if (data.isInsertOption()) {
                new UserGuaNobleRelationDaoImpl().add(data);
            } else if (data.isUpdateOption()) {
                new UserGuaNobleRelationDaoImpl().update(data);
            }
        }

        List<UserGuaGiftData> saveList = new ArrayList<>();
        synchronized (needUpdateGiftList) {
            saveList.addAll(needUpdateGiftList);
            needUpdateGiftList.clear();
        }

        for (UserGuaGiftData userGuaGiftData : saveList) {
            if (userGuaGiftData.isInsertOption()) {
                new UserGuaGiftDaoImpl().add(userGuaGiftData);
            } else if (userGuaGiftData.isUpdateOption()) {
                new UserGuaGiftDaoImpl().update(userGuaGiftData);
            }
        }


        return true;
    }

    @Override
    public void afterLogin() {
        initUserData();
        resetOneDay(true);
        removeOverBroadcastId();
        syncUserData();
        loginReqBroadcast();
        syncAllOpenServerList();
    }

    public void initSystem() {
        initUserData();
        syncUserData();
    }

    public boolean isSystemOpen() {
        return SystemOpenMgr.systemOpen(player, eSystemId.GuaGifts.getValue());
    }

    public int checkActivityRet() {
        if (userData == null) {
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        if (GuaGiftsMgr.getConfig() == null || GuaGiftsMgr.getConfig().getActivityId() != userData.getActivityId()) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }

        if (!ActivityMgr.activityInTime(GuaGiftsMgr.getConfig().getActivityInfo())) {
            return GameErrorCode.E_ACTIVITY_OVER_TIME;
        }

        return 0;
    }

    public int checkActivityShowRet() {
        if (userData == null) {
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        if (GuaGiftsMgr.getConfig() == null || GuaGiftsMgr.getConfig().getActivityId() != userData.getActivityId()) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }

        if (!ActivityMgr.activityInShowTime(GuaGiftsMgr.getConfig().getActivityInfo())) {
            return GameErrorCode.E_ACTIVITY_OVER_TIME;
        }

        return 0;
    }

    public synchronized void initUserData() {
        if (!isSystemOpen()) {
            return;
        }

        GuaGiftsConfig config = GuaGiftsMgr.getConfig();
        if (config == null) {
            return;
        }
        if (null == userData || userData.getActivityId() != config.getActivityId()) {
            userData = new UserGuaData(config.getActivityId(), player.getUserId());
            userRelationMap.clear();
            userNobleRelationMap.clear();
            userNobleGiftList.clear();
        }
    }

    public void syncUserData() {
        if (userData == null) {
            return;
        }
        if (player.getState() != PlayerState.ONLINE) {//玩家在线才执行
            return;
        }
        GuaGiftsProto.GuaGiftsUserSyncMsg.Builder syncMsg = GuaGiftsProto.GuaGiftsUserSyncMsg.newBuilder();
        syncMsg.setActivityId(userData.getActivityId());
        syncMsg.setNobleRankValue(userData.getNobleValue());
        syncMsg.setGuaRankValue(userData.getGuaValue());
        syncMsg.setSendNobleGiftCount(userData.getSendNobleCount());
        syncMsg.setHaveGift(!userNobleGiftList.isEmpty());

        for (Map.Entry<Integer, Integer> entry : userData.getDayCountMap().entrySet()) {
            GuaGiftsProto.GuaGiftsDayCountTemp.Builder dayCountBuilder = GuaGiftsProto.GuaGiftsDayCountTemp.newBuilder();
            dayCountBuilder.setGoodsId(entry.getKey());
            dayCountBuilder.setCount(entry.getValue());
            syncMsg.addDayCount(dayCountBuilder);
        }

        player.sendPacket(ClientProtocol.U_GUAGIFTS_USER_SYNC, syncMsg);
    }

    public void loginReqBroadcast() {
        int ret = checkActivityShowRet();
        if (ret != 0) {
            return;
        }
        GuaGiftsProto.CrossLoginGetGiftBroadcastReqMsg.Builder crossMsg = GuaGiftsProto.CrossLoginGetGiftBroadcastReqMsg.newBuilder();
        crossMsg.setActivityId(GuaGiftsMgr.getConfig().getActivityId());
        crossMsg.addAllExcludeId(userData.getWatchBroadcastList());
        player.sendPacket(CrossProtocol.C_GUAGIFTS_LOGIN_GET_GIFT_BROADCAST, crossMsg);
    }

    public void resetOneDay(boolean isLogin) {
        if (userData == null) {
            return;
        }
        long currentTime = DateHelper.getCurrentTime();
        if (!DateHelper.isSameDay(currentTime / 1000, userData.getLastGetTime() / 1000)) {
            userData.setDayCountMap(new HashMap<>());
            userData.setLastGetTime(currentTime);
            if (!isLogin) {
                syncUserData();
            }
        }
    }

    public UserGuaRelationData getTargetRelation(long targetUserId) {
        return userRelationMap.get(targetUserId);
    }

    public void addTargetRelation(UserGuaRelationData relationData) {
        synchronized (userRelationMap) {
            userRelationMap.put(relationData.getTargetUserId(), relationData);
        }
    }

    public UserGuaNobleRelationData getNobleTargetRelation(long targetUserId) {
        return userNobleRelationMap.get(targetUserId);
    }

    public void addNobleTargetRelation(UserGuaNobleRelationData relationData) {
        synchronized (userNobleRelationMap) {
            userNobleRelationMap.put(relationData.getTargetUserId(), relationData);
        }
    }

    /**
     * 2	商会页签展示排序
     * 1	优先展示商会中有互动的玩家
     * 1	玩家赠送过花的对象
     * 2	玩家收到过花的对象
     * 2	都有互动时，优先展示赠花/收花数量大的人员
     * 2	赠花/收花数量相同时，赠花的在前面
     * 3	赠花也相同时，对方赚速高的在前面
     * <p>
     * 3	世交页签展示排序
     * 1	优先展示世交中有互动的玩家
     * 1	玩家赠送过花的对象
     * 2	玩家收到过花的对象
     * 2	都有互动时，优先展示赠花/收花数量大的人员
     * 2	赠花/收花数量相同时，赠花的在前面
     * 3	赠花也相同时，对方赚速高的在前面
     * <p>
     * 4	往来页签展示排序
     * 1	往来页签中，只显示有互动的玩家
     * 1	玩家赠送过花的对象
     * 2	玩家收到过花的对象
     * 2	往来人员排序规则
     * 1	优先展示赠花/收花数量大的人员
     * 2	赠花/收花数量相同时，赠花的在前面
     * 3	赠花也相同时，对方赚速高的在前面
     * 3	往来页签中，最多显示20人。
     *
     * @param tapType
     * @return
     */
    public int getRelationList(int giftType, int tapType) {
        int ret = checkActivityShowRet();
        if (ret != 0) {
            return ret;
        }

        GuaGiftsProto.GuaGiftsRelationListRespMsg.Builder toClientMsg = GuaGiftsProto.GuaGiftsRelationListRespMsg.newBuilder();
        toClientMsg.setRet(0);
        toClientMsg.setActivityId(GuaGiftsMgr.getConfig().getActivityId());
        toClientMsg.setTapType(tapType);
        toClientMsg.setGiftType(giftType);
        if (tapType == 1) {//商会成员
            String unionUid = player.getUserInfo().getUnionUid();
            CrossUnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
            if (unionInfo != null) {
                Map<Long, CrossUnionMember> unionMemberMap = CrossUnionMgr.getUnionMemberMap(unionUid);
                for (CrossUnionMember unionMember : unionMemberMap.values()) {
                    if (unionMember.getUserId() == player.getUserId()) {
                        continue;
                    }
                    GuaGiftsProto.GuaGiftsRelationTemp.Builder relationTemp = GuaGiftsProto.GuaGiftsRelationTemp.newBuilder();
                    relationTemp.setTargetUserId(unionMember.getUserId());
                    relationTemp.setTargetServerId(unionMember.getServerId());
                    toClientMsg.addRelationList(relationTemp);
                }
            }
        } else if (tapType == 2) {//世家
            Map<Long, RelativesInfo> relativesMap = player.getModule(RelativesModule.class).getRelativesMap();
            for (RelativesInfo relativesInfo : relativesMap.values()) {
                if (relativesInfo.getStatus() != 1) {
                    continue;
                }
                long targetUserId = 0;
                if (relativesInfo.getUserId1() == player.getUserId()) {
                    targetUserId = relativesInfo.getUserId2();
                } else {
                    targetUserId = relativesInfo.getUserId1();
                }
                long targetServerId = CommonMgr.getTargetServerIdByUserId(targetUserId);
                GuaGiftsProto.GuaGiftsRelationTemp.Builder relationTemp = GuaGiftsProto.GuaGiftsRelationTemp.newBuilder();
                relationTemp.setTargetUserId(targetUserId);
                relationTemp.setTargetServerId(targetServerId);
                toClientMsg.addRelationList(relationTemp);
            }
        } else if (tapType == 3) {//往来关系前20
            if (giftType == 1) {
                List<UserGuaNobleRelationData> relationDataList = new ArrayList<>();
                synchronized (userNobleRelationMap) {
                    relationDataList.addAll(userNobleRelationMap.values());
                }
                relationDataList.sort((o1, o2) -> {
                    int compare = Integer.compare(o2.getGetCount() + o2.getSendCount(), o1.getGetCount() + o1.getSendCount());
                    if (compare == 0) {
                        compare = Integer.compare(o2.getSendCount(), o1.getSendCount());
                    }
                    if (compare == 0) {
                        compare = Integer.compare(o2.getGetCount(), o1.getGetCount());
                    }
                    if (compare == 0) {
                        compare = Long.compare(o1.getSendTime(), o2.getSendTime());
                    }

                    return compare;
                });

                for (int i = 0; i < relationDataList.size() && i < GuaGiftsMgr.getConfig().getGIVE_AWAY_RECORD(); i++) {
                    UserGuaNobleRelationData guaRelationData = relationDataList.get(i);
                    long targetUserId = guaRelationData.getTargetUserId();
                    long targetServerId = CommonMgr.getTargetServerIdByUserId(targetUserId);
                    GuaGiftsProto.GuaGiftsRelationTemp.Builder relationTemp = GuaGiftsProto.GuaGiftsRelationTemp.newBuilder();
                    relationTemp.setTargetUserId(guaRelationData.getTargetUserId());
                    relationTemp.setTargetServerId(targetServerId);
                    toClientMsg.addRelationList(relationTemp);
                }
            } else if (giftType == 2) {
                List<UserGuaRelationData> relationDataList = new ArrayList<>();
                synchronized (userRelationMap) {
                    relationDataList.addAll(userRelationMap.values());
                }
                relationDataList.sort((o1, o2) -> {
                    int compare = Integer.compare(o2.getGetCount() + o2.getSendCount(), o1.getGetCount() + o1.getSendCount());
                    if (compare == 0) {
                        compare = Integer.compare(o2.getSendCount(), o1.getSendCount());
                    }
                    if (compare == 0) {
                        compare = Integer.compare(o2.getGetCount(), o1.getGetCount());
                    }
                    if (compare == 0) {
                        compare = Long.compare(o1.getSendTime(), o2.getSendTime());
                    }

                    return compare;
                });

                for (int i = 0; i < relationDataList.size() && i < GuaGiftsMgr.getConfig().getGIVE_AWAY_RECORD(); i++) {
                    UserGuaRelationData guaRelationData = relationDataList.get(i);
                    long targetUserId = guaRelationData.getTargetUserId();
                    long targetServerId = CommonMgr.getTargetServerIdByUserId(targetUserId);
                    GuaGiftsProto.GuaGiftsRelationTemp.Builder relationTemp = GuaGiftsProto.GuaGiftsRelationTemp.newBuilder();
                    relationTemp.setTargetUserId(guaRelationData.getTargetUserId());
                    relationTemp.setTargetServerId(targetServerId);
                    toClientMsg.addRelationList(relationTemp);
                }
            }

        }

        GuaGiftsProto.CrossGuaGetTargetRankValueReqMsg.Builder crossMsg = GuaGiftsProto.CrossGuaGetTargetRankValueReqMsg.newBuilder();
        crossMsg.setActivityId(GuaGiftsMgr.getConfig().getActivityId());
        if (giftType == 1) {
            crossMsg.setConditionType(eGamePlayerEventType.GuaGiftsNobleRank.getValue());
        } else {
            crossMsg.setConditionType(eGamePlayerEventType.GuaGiftsGuaRank.getValue());
        }
        crossMsg.setToClientMsg(toClientMsg);

        //发到活动跨服拉榜单值
        player.sendPacket(CrossProtocol.C_GUAGIFTS_CONCAT_TARGET_RANK_VALUE, crossMsg);
        return 0;
    }

    public void getRelationListCrossBack(GuaGiftsProto.GuaGiftsRelationListRespMsg resultMsg) {
        int tapType = resultMsg.getTapType();
        int giftType = resultMsg.getGiftType();

        Map<Long, Set<Long>> needUserInfoFromOtherServer = new HashMap<>();

        GuaGiftsProto.GuaGiftsRelationListRespMsg.Builder resultBuilder = resultMsg.toBuilder();
        for (int i = 0; i < resultBuilder.getRelationListBuilderList().size(); i++) {
            GuaGiftsProto.GuaGiftsRelationTemp.Builder tempBuilder = resultBuilder.getRelationListBuilder(i);
            long targetUserId = tempBuilder.getTargetUserId();
            if (giftType == 1) {
                if (tempBuilder.getTotalGiftCount() > 0) {
                    cacheTargetNobleTotalCountMap.put(targetUserId, tempBuilder.getTotalGiftCount());
                }

                UserGuaNobleRelationData targetRelation = getNobleTargetRelation(targetUserId);
                if (targetRelation != null) {
                    tempBuilder.setGetGiftCount(targetRelation.getGetCount());
                    tempBuilder.setSendGiftCount(targetRelation.getSendCount());
                } else {
                    tempBuilder.setGetGiftCount(0);
                    tempBuilder.setSendGiftCount(0);
                }
            } else {
                if (tempBuilder.getTotalGiftCount() > 0) {
                    cacheTargetGuaTotalCountMap.put(targetUserId, tempBuilder.getTotalGiftCount());
                }

                UserGuaRelationData targetRelation = getTargetRelation(targetUserId);
                if (targetRelation != null) {
                    tempBuilder.setGetGiftCount(targetRelation.getGetCount());
                    tempBuilder.setSendGiftCount(targetRelation.getSendCount());
                } else {
                    tempBuilder.setGetGiftCount(0);
                    tempBuilder.setSendGiftCount(0);
                }
            }


            UserBaseInfo userBaseInfo = UserMgr.getUserBaseInfo(targetUserId, GameServer.getInstance().getServerId());
            if (userBaseInfo == null) {
                //本服没有去商会找一下
                CrossUnionMember unionMember = CrossUnionMgr.getUnionMember(targetUserId);
                if (unionMember == null) {
                    //商会也没有跨服拉一下
                    long targetServerId = RelativesMgr.getUserServerId(targetUserId);
                    Set<Long> userIds = needUserInfoFromOtherServer.get(targetServerId);
                    if (userIds == null) {
                        userIds = new HashSet<>();
                        needUserInfoFromOtherServer.put(targetServerId, userIds);
                    }
                    userIds.add(targetUserId);

                    continue;
                } else {
                    userBaseInfo = unionMember.getUserBaseInfo();
                }
            }

            tempBuilder.setUserBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));

            resultBuilder.setRelationList(i, tempBuilder);
        }

        player.sendPacket(ClientProtocol.U_GUAGIFTS_GET_RELATION_LIST, resultBuilder);

        //跨服拉userInfo
        //这里是本服拉不到userInfo,跨服去拉过来分批发给客户端
        if (!needUserInfoFromOtherServer.isEmpty()) {
            for (Map.Entry<Long, Set<Long>> entry : needUserInfoFromOtherServer.entrySet()) {
                Long serverId = entry.getKey();
                Set<Long> userIds = entry.getValue();

                QixiProto.QixiGetUserInfoReqMsg.Builder reqMsg = QixiProto.QixiGetUserInfoReqMsg.newBuilder();
                reqMsg.setActivityId(GuaGiftsMgr.getConfig().getActivityId());
                reqMsg.addAllTargetUserId(userIds);
                reqMsg.setReqProtocolType(GameProtocol.S_GUAGIFTS_GET_RELATION_LIST);

                QixiProto.QixiGetUserInfoRespMsg.Builder resp = QixiProto.QixiGetUserInfoRespMsg.newBuilder();

                CompletableFuture<SyncResponse> future = GamePlayerMgr.sendToGameServer(serverId, GameProtocol.S_QIXI_GET_USER_INFO, player.getUserId(), reqMsg, resp);
                future.thenAccept((SyncResponse syncResponse) -> {
                    GuaGiftsProto.GuaGiftsRelationListRespMsg.Builder builder = GuaGiftsProto.GuaGiftsRelationListRespMsg.newBuilder();
                    builder.setRet(0);

                    if (syncResponse.getErrorCode() != 0) {
                        builder.setRet(syncResponse.getErrorCode());
                    }
                    if (resp.getReqProtocolType() != GameProtocol.S_GUAGIFTS_GET_RELATION_LIST) {
                        return;
                    }

                    builder.setGiftType(giftType);
                    builder.setTapType(tapType);

                    builder.setActivityId(GuaGiftsMgr.getConfig().getActivityId());

                    for (QixiProto.QixiRelationTemp temp : resp.getRelationListList()) {
                        long targetUserId = temp.getTargetUserId();
                        GuaGiftsProto.GuaGiftsRelationTemp.Builder relationTemp = GuaGiftsProto.GuaGiftsRelationTemp.newBuilder();
                        relationTemp.setUserBaseInfo(temp.getUserBaseInfo());
                        relationTemp.setTargetUserId(temp.getTargetUserId());
                        relationTemp.setGetGiftCount(0);
                        relationTemp.setSendGiftCount(0);
                        if (giftType == 1) {
                            UserGuaNobleRelationData targetRelation = getNobleTargetRelation(targetUserId);
                            if (targetRelation != null) {
                                relationTemp.setGetGiftCount(targetRelation.getGetCount());
                                relationTemp.setSendGiftCount(targetRelation.getSendCount());
                            }
                            Integer totalValue = cacheTargetNobleTotalCountMap.getOrDefault(targetUserId, 0);
                            relationTemp.setTotalGiftCount(totalValue);
                        } else {
                            UserGuaRelationData targetRelation = getTargetRelation(targetUserId);
                            if (targetRelation != null) {
                                relationTemp.setGetGiftCount(targetRelation.getGetCount());
                                relationTemp.setSendGiftCount(targetRelation.getSendCount());
                            }
                            Integer totalValue = cacheTargetGuaTotalCountMap.getOrDefault(targetUserId, 0);
                            relationTemp.setTotalGiftCount(totalValue);
                        }
                        builder.addRelationList(relationTemp);
                    }

                    player.sendPacket(ClientProtocol.U_GUAGIFTS_GET_RELATION_LIST, builder);
                });
            }
        }
    }

    /**
     * 送花
     *
     * @param reqMsg
     * @return
     */
    public synchronized int sendGift(GuaGiftsProto.GuaGiftsSendGiftReqMsg reqMsg) {
        int ret = checkActivityRet();
        if (ret != 0) {
            return ret;
        }

        int giftType = reqMsg.getGiftType();
        if (reqMsg.getTargetUserId() == player.getUserId() && giftType == 1) {//贵族榜不能送自己
            return GameErrorCode.E_GUAGIFTS_CAN_NOT_SEND_SELF;
        }
        if (!GuaGiftsMgr.getConfig().isRightGift(giftType, reqMsg.getGiftId())) {
            return GameErrorCode.E_GUAGIFTS_GIFT_USE_CONFIG_NOT_FOUND;
        }

        //物品类别161 花满七夕道具  参数列表：送花数|戒指id|戒指数量|每日赠送上限|是否广播,   赠送上限-1表示无限制，0表示不广播，1广播
        GoodsInfo giftInfo = GoodsMgr.getGoodsById(reqMsg.getGiftId());
        if (giftInfo == null) {
            return GameErrorCode.E_GUAGIFTS_GIFT_USE_CONFIG_NOT_FOUND;
        }

        String content = reqMsg.getContent();
        if (giftInfo.getParamList().get(4).intValue() == 1) {//需要广播的才判断宣言
            //编辑限制
            GameEditLimit gameEditLimit = GameEditLimitMgr.getGameEditLimit(Protocol.S_GUAGIFTS_SEND_GIFTS);
            if (null != gameEditLimit) {
                long nowTime = System.currentTimeMillis();
                if (nowTime >= gameEditLimit.getLimitEditStartTime() && nowTime < gameEditLimit.getLimitEditEndTime()) {
                    String replaceStr = ServerLanguageMgr.getContent(GuaGiftsMgr.getConfig().getBROADCASTING_CONTENT(), player.getLanguage());
                    if (!StringUtils.isNullOrEmpty(gameEditLimit.getReplaceContent())) {
                        replaceStr = gameEditLimit.getReplaceContent();
                    }
                    content = replaceStr;
                }
            }
            /**
             * 送财功能被禁用 则返回系统未开放
             */
            if (ForbiddenMgr.isForbiddenCmd(player.getUserId(), Protocol.S_GUAGIFTS_SEND_GIFTS)) {
                return GameErrorCode.E_SYSTEM_NO_OPEN;
            }

            //留言屏蔽字判断
            if (ForbiddenWordMgr.isForbidden(content)) {
                return GameErrorCode.E_FORBIDDEN_WORD;
            }
            if (StringUtils.isNullOrEmpty(content)) {
                return GameErrorCode.E_FORBIDDEN_WORD;
            }
        } else {//不要广播的给个空字符串
            content = "";
        }


        int giftUseNum = reqMsg.getGiftCount();
        Property cost = new Property(giftInfo.getGoodsId(), giftUseNum);

        if (giftUseNum == 0 || !player.getModule(CurrencyModule.class).currencyIsEnough(cost)) {
            return Integer.valueOf(GameErrorCode.E_BAG_ITEM_NO_ENOUGH);
        }

        if (giftUseNum > giftInfo.getCanUse()) {
            return GameErrorCode.E_GUAGIFTS_ONLY_SEND_ONE_GIFT;
        }

        long targetServerId = CommonMgr.getTargetServerIdByUserId(reqMsg.getTargetUserId());

        if (waitSendGiftBackUserIdSet.contains(reqMsg.getTargetUserId())) {
            GuaGiftsProto.GuaGiftsSendGiftRespMsg.Builder waiMsg = GuaGiftsProto.GuaGiftsSendGiftRespMsg.newBuilder();
            waiMsg.setRet(GameErrorCode.E_GUAGIFTS_WAIT_SEND_GIFT_BACK);
            player.sendPacket(ClientProtocol.U_GUAGIFTS_WAIT_SEND_GIFTS_BACK, waiMsg);
            return -1;//返回-1等异步处理。
        }

        waitSendGiftBackUserIdSet.add(reqMsg.getTargetUserId());

        if (targetServerId == GameServer.getInstance().getServerId()) {//本服送花
            GuaGiftsProto.CrossGuaGiftsSendGiftRespMsg.Builder backMsg = GuaGiftsMgr.receiveGift(GameServer.getInstance().getServerId(), player.getUserId(), reqMsg.getTargetUserId(), reqMsg.getGiftId(), giftUseNum, content);
            if (backMsg == null) {
                GuaGiftsProto.GuaGiftsSendGiftRespMsg.Builder waiMsg = GuaGiftsProto.GuaGiftsSendGiftRespMsg.newBuilder();
                waiMsg.setRet(GameErrorCode.E_GUAGIFTS_WAIT_SEND_GIFT_BACK);
                player.sendPacket(ClientProtocol.U_GUAGIFTS_WAIT_SEND_GIFTS_BACK, waiMsg);
                return -1;//返回-1等异步处理。
            }

            player.getModule(PreReduceModule.class).preReduce(cost);//统一预扣

            sendGiftSuccessBack(backMsg.build());

            return 0;
        } else {//跨服送花
            GuaGiftsProto.GuaGiftsSendGiftReqMsg.Builder builder = GuaGiftsProto.GuaGiftsSendGiftReqMsg.newBuilder();
            builder.setActivityId(GuaGiftsMgr.getConfig().getActivityId());
            builder.setTargetUserId(reqMsg.getTargetUserId());
            builder.setGiftCount(reqMsg.getGiftCount());
            builder.setGiftId(reqMsg.getGiftId());
            builder.setContent(content);
            builder.setGiftType(giftType);

            GuaGiftsProto.CrossGuaGiftsSendGiftRespMsg.Builder resp = GuaGiftsProto.CrossGuaGiftsSendGiftRespMsg.newBuilder();

            player.getModule(PreReduceModule.class).preReduce(cost);//统一预扣

            CompletableFuture<SyncResponse> future = GamePlayerMgr.sendToGameServer(targetServerId, GameProtocol.S_GUAGIFTS_SEND_GIFTS, player.getUserId(), builder, resp);
            future.thenAccept((SyncResponse syncResponse) -> {
                if (syncResponse.getErrorCode() != 0) {
                    resp.setRet(syncResponse.getErrorCode());
                }
                if (resp.getRet() != -1) {
                    sendGiftSuccessBack(resp.build());
                } else {
                    GuaGiftsProto.GuaGiftsSendGiftRespMsg.Builder waiMsg = GuaGiftsProto.GuaGiftsSendGiftRespMsg.newBuilder();
                    waiMsg.setRet(GameErrorCode.E_GUAGIFTS_WAIT_SEND_GIFT_BACK);
                    player.sendPacket(ClientProtocol.U_GUAGIFTS_WAIT_SEND_GIFTS_BACK, waiMsg);
                }
            });

            return -1;
        }
    }

    public synchronized void sendGiftSuccessBack(GuaGiftsProto.CrossGuaGiftsSendGiftRespMsg resp) {

        int giftType = GuaGiftsMgr.getConfig().getGiftTypeByGiftId(resp.getGiftId());
        waitSendGiftBackUserIdSet.remove(resp.getTargetUserId());

        Property cost = new Property(resp.getGiftId(), resp.getGiftCount());
        player.getModule(PreReduceModule.class).restorePreReduce(cost);//统一返还预扣

        GuaGiftsProto.GuaGiftsSendGiftRespMsg.Builder resultMsg = GuaGiftsProto.GuaGiftsSendGiftRespMsg.newBuilder();
        resultMsg.setRet(resp.getRet());
        resultMsg.setRemainCanReceive(resp.getRemainCanReceive());
        if (resp.getRet() == 0) {
            long currentTime = DateHelper.getCurrentTime();
            player.getModule(CurrencyModule.class).removeCurrency(cost, eLogMoneyType.GuaGiftsActivity, eLogMoneyType.GuaGiftsActivitySendGiftCost);

            GoodsInfo giftInfo = GoodsMgr.getGoodsById(resp.getGiftId());
            Property giftReward = GuaGiftsMgr.getGiftReward(giftInfo, resp.getGiftCount());
            if (!giftReward.isNothing()) {
                player.getModule(CurrencyModule.class).addCurrency(giftReward, eLogMoneyType.GuaGiftsActivity, eLogMoneyType.GuaGiftsActivitySendGiftReward);
            }

            resultMsg.setActivityId(GuaGiftsMgr.getConfig().getActivityId());
            resultMsg.setReward(PropertyHelper.parsePropertyToString(giftReward));
            resultMsg.setSendTime(currentTime);
            resultMsg.setGiftId(resp.getGiftId());
            resultMsg.setGiftCount(resp.getGiftCount());
            resultMsg.setTargetServerId(resp.getUserBaseInfo().getServerId());
            resultMsg.setTargetName(resp.getUserBaseInfo().getNickName());

            player.sendPacket(ClientProtocol.U_GUAGIFTS_SEND_GIFTS, resultMsg);

            int addCount = giftInfo.getParamList().get(0).multiply(BigInteger.valueOf(resp.getGiftCount())).intValue();
            //贵族送礼只加自己的榜单值,孤寡送礼加对方的榜单值
            if (giftType == 1) {
                synchronized (userNobleRelationMap) {
                    UserGuaNobleRelationData targetRelation = getNobleTargetRelation(resp.getTargetUserId());
                    if (targetRelation == null) {
                        targetRelation = new UserGuaNobleRelationData(GuaGiftsMgr.getConfig().getActivityId(), player.getUserId(), resp.getTargetUserId());
                        addNobleTargetRelation(targetRelation);
                    }

                    targetRelation.setSendCount(targetRelation.getSendCount() + addCount);
                    targetRelation.setSendTime(currentTime);

                    int totalSendCount = 0;
                    for (UserGuaNobleRelationData relationData : userNobleRelationMap.values()) {
                        totalSendCount += relationData.getSendCount();
                    }

                    userData.setSendNobleCount(totalSendCount);
                    userData.setNobleValue(totalSendCount);
                }
                player.notifyListener(eGamePlayerEventType.GuaGiftsSendNobleGift.getValue(), userData.getSendNobleCount());

                player.notifyListener(eGamePlayerEventType.GuaGiftsNobleRank.getValue(), userData.getNobleValue());
            } else if (giftType == 2) {
                synchronized (userRelationMap) {
                    UserGuaRelationData targetRelation = getTargetRelation(resp.getTargetUserId());
                    if (targetRelation == null) {
                        targetRelation = new UserGuaRelationData(GuaGiftsMgr.getConfig().getActivityId(), player.getUserId(), resp.getTargetUserId());
                        addTargetRelation(targetRelation);
                    }

                    targetRelation.setSendCount(targetRelation.getSendCount() + addCount);
                    targetRelation.setSendTime(currentTime);
                }
            }


            AutoLogMgr.add(new LogGuaGiftsSendGift(GuaGiftsMgr.getConfig().getActivityId(), player.getUserId(), resp.getTargetUserId(), resp.getGiftId(), resp.getGiftCount(), addCount));

            if (giftInfo.getParamList().get(4).intValue() == 1) {
                //广播,发到跨服创建数据
                GuaGiftsProto.CrossGuaGiftsGiftBroadcastMsg.Builder toCrossMsg = GuaGiftsProto.CrossGuaGiftsGiftBroadcastMsg.newBuilder();
                toCrossMsg.setActivityId(GuaGiftsMgr.getConfig().getActivityId());
                toCrossMsg.setLeftUserId(player.getUserId());
                toCrossMsg.setRightUserId(resp.getTargetUserId());
                toCrossMsg.setGiftId(resp.getGiftId());
                toCrossMsg.setContent(resp.getContent());

                toCrossMsg.setLeftUserInfo(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.parseUserBaseInfo(player.getUserInfo(), GameServer.getInstance().getServerId())));
                toCrossMsg.setRightUserInfo(resp.getUserBaseInfo());
                toCrossMsg.setSendTime(currentTime);

                player.sendPacket(CrossProtocol.C_GUAGIFTS_SEND_GIFT_BROADCAST, toCrossMsg);

                long targetServerId = toCrossMsg.getRightUserInfo().getServerId();
                if (!GuaGiftsMgr.getConfig().getActivityInfo().getServerIdList().contains(targetServerId)) {
                    //不在同一个活动服,发到另外一个活动服
                    GamePlayerMgr.sendToGameServer(targetServerId, GameProtocol.S_GUAGIFTS_GIFT_BROADCAST_FROM_OTHER, player.getUserId(), toCrossMsg, null);
                }
            }
        } else {
            player.sendPacket(ClientProtocol.U_GUAGIFTS_SEND_GIFTS, resultMsg);
        }
    }


    /**
     * 收花
     */
    public synchronized GuaGiftsProto.CrossGuaGiftsSendGiftRespMsg.Builder receiveGift(long sendUserId, int giftId, int giftCount, String content) {
        //收花的人如果没有活动数据,直接返回0,不往下走。策划又改了,不让收了, 不能往下走。
        GuaGiftsProto.CrossGuaGiftsSendGiftRespMsg.Builder resultMsg = GuaGiftsProto.CrossGuaGiftsSendGiftRespMsg.newBuilder();
        resultMsg.setRet(0);
        initUserData();
        int ret = checkActivityRet();
        if (ret != 0) {
            return resultMsg.setRet(ret);
        }
        resetOneDay(false);

        GoodsInfo giftInfo = GoodsMgr.getGoodsById(giftId);

        if (giftInfo == null) {
            return resultMsg.setRet(GameErrorCode.E_GUAGIFTS_GIFT_USE_CONFIG_NOT_FOUND);
        }
        int addCount = giftInfo.getParamList().get(0).multiply(BigInteger.valueOf(giftCount)).intValue();

        int giftType = GuaGiftsMgr.getConfig().getGiftTypeByGiftId(giftId);

        if (giftType == 1) {
            synchronized (userNobleRelationMap) {
                int receiveLimit = giftInfo.getParamList().get(3).intValue();
                int remainCanReceive = -1;
                resultMsg.setRemainCanReceive(remainCanReceive);
                if (receiveLimit != -1) {
                    //有接收数量限制
                    int dayCount = userData.getDayCountMap().getOrDefault(giftId, 0);

                    if (dayCount >= receiveLimit) {
                        resultMsg.setRemainCanReceive(receiveLimit - dayCount);
                        return resultMsg.setRet(GameErrorCode.E_GUAGIFTS_GIFT_RECEIVE_LIMIT);
                    }

                    if (dayCount + giftCount > receiveLimit) {
                        resultMsg.setRemainCanReceive(receiveLimit - dayCount);
                        return resultMsg.setRet(GameErrorCode.E_GUAGIFTS_GIFT_RECEIVE_LIMIT);
                    }else {
                        remainCanReceive = receiveLimit - (dayCount + giftCount);
                        resultMsg.setRemainCanReceive(remainCanReceive);
                    }
                }

                if (userNobleGiftList.size() >= GuaGiftsMgr.getConfig().getGIFT_LIMIT()) {
                    return resultMsg.setRet(GameErrorCode.E_GUAGIFTS_GIFT_LIMIT);
                }

                UserGuaNobleRelationData targetRelation = getNobleTargetRelation(sendUserId);
                if (targetRelation == null) {
                    targetRelation = new UserGuaNobleRelationData(GuaGiftsMgr.getConfig().getActivityId(), player.getUserId(), sendUserId);
                    addNobleTargetRelation(targetRelation);
                }
                targetRelation.setGetCount(targetRelation.getGetCount() + addCount);
                targetRelation.setGetTime(System.currentTimeMillis());

                userData.addDayCount(giftId, giftCount);

                int totalValue = 0;

                for (UserGuaRelationData relationData : userRelationMap.values()) {
                    totalValue += relationData.getGetCount();
                }

                userData.setLastGetTime(System.currentTimeMillis());
            }

        } else if (giftType == 2) {
            synchronized (userRelationMap) {
                int receiveLimit = giftInfo.getParamList().get(3).intValue();
                int remainCanReceive = -1;
                resultMsg.setRemainCanReceive(remainCanReceive);
                if (receiveLimit != -1) {
                    //有接收数量限制
                    int dayCount = userData.getDayCountMap().getOrDefault(giftId, 0);

                    if (dayCount >= receiveLimit) {
                        resultMsg.setRemainCanReceive(receiveLimit - dayCount);
                        return resultMsg.setRet(GameErrorCode.E_GUAGIFTS_GIFT_RECEIVE_LIMIT);
                    }

                    if (dayCount + giftCount > receiveLimit) {
                        resultMsg.setRemainCanReceive(receiveLimit - dayCount);
                        return resultMsg.setRet(GameErrorCode.E_GUAGIFTS_GIFT_RECEIVE_LIMIT);
                    }else {
                        remainCanReceive = receiveLimit - (dayCount + giftCount);
                        resultMsg.setRemainCanReceive(remainCanReceive);
                    }
                }

                UserGuaRelationData targetRelation = getTargetRelation(sendUserId);
                if (targetRelation == null) {
                    targetRelation = new UserGuaRelationData(GuaGiftsMgr.getConfig().getActivityId(), player.getUserId(), sendUserId);
                    addTargetRelation(targetRelation);
                }
                targetRelation.setGetCount(targetRelation.getGetCount() + addCount);
                targetRelation.setGetTime(System.currentTimeMillis());

                userData.addDayCount(giftId, giftCount);

                int totalValue = 0;

                for (UserGuaRelationData relationData : userRelationMap.values()) {
                    totalValue += relationData.getGetCount();
                }

                userData.setGuaValue(totalValue);
                userData.setLastGetTime(System.currentTimeMillis());

                player.notifyListener(eGamePlayerEventType.GuaGiftsGuaRank.getValue(), userData.getGuaValue());
            }
        }

        //添加赠礼日志,贵族送礼才有礼物
        UserGuaGiftData userGuaGiftData = new UserGuaGiftData(GuaGiftsMgr.getConfig().getActivityId(), player.getUserId(), sendUserId, System.currentTimeMillis(), giftType);
        userGuaGiftData.setGoodsId(giftId);
        userGuaGiftData.setGoodsCount(giftCount);
//        userGuaGiftData.setContent(content);礼物用不到宣言,不存

        addNewGift(userGuaGiftData);

        AutoLogMgr.add(new LogGuaGiftsReceiveGift(GuaGiftsMgr.getConfig().getActivityId(), player.getUserId(), sendUserId, giftId, giftCount, addCount));

        if (player.getState() == PlayerState.ONLINE) {//玩家在线才执行
            syncUserData();
        }

        return resultMsg;
    }

    public void addNewGift(UserGuaGiftData userGuaGiftData) {
        if (userGuaGiftData == null) {
            return;
        }

        if (userGuaGiftData.getGiftType() == 1) {
            synchronized (userNobleGiftList) {
                userNobleGiftList.add(userGuaGiftData);
            }
        } else if (userGuaGiftData.getGiftType() == 2) {
            synchronized (userGuaGiftList) {
                userGuaGiftList.add(userGuaGiftData);
                while (userGuaGiftList.size() > GuaGiftsMgr.getConfig().getGIFT_LIMIT()) {
                    userGuaGiftList.remove(0);
                }
            }
        }

        synchronized (needUpdateGiftList) {
            needUpdateGiftList.add(userGuaGiftData);
        }

    }

    public int searchUser(GuaGiftsProto.GuaGiftsSearchUserReqMsg reqMsg) {
        int ret = checkActivityRet();
        if (ret != 0) {
            return ret;
        }
        int giftType = reqMsg.getGiftType();

        if (reqMsg.getServerId() == GameServer.getInstance().getServerId()) {
            GuaGiftsProto.GuaGiftsSearchUserRespMsg.Builder respMsg = GuaGiftsMgr.searchUser(reqMsg.getTargetAliasId(), giftType);
            if (respMsg.getRet() != 0) {
                return respMsg.getRet();
            }
            if (giftType == 1){
                UserGuaNobleRelationData targetRelation = getNobleTargetRelation(respMsg.getUserRelation().getTargetUserId());
                if (targetRelation != null) {
                    GuaGiftsProto.GuaGiftsRelationTemp.Builder relationTemp = GuaGiftsProto.GuaGiftsRelationTemp.newBuilder();
                    relationTemp.setTargetUserId(targetRelation.getTargetUserId());
                    relationTemp.setUserBaseInfo(respMsg.getUserRelation().getUserBaseInfo());
                    relationTemp.setSendGiftCount(targetRelation.getSendCount());
                    relationTemp.setGetGiftCount(targetRelation.getGetCount());
                    relationTemp.setTotalGiftCount(respMsg.getUserRelation().getTotalGiftCount());
                    respMsg.setUserRelation(relationTemp);
                }
            }else{
                UserGuaRelationData targetRelation = getTargetRelation(respMsg.getUserRelation().getTargetUserId());
                if (targetRelation != null) {
                    GuaGiftsProto.GuaGiftsRelationTemp.Builder relationTemp = GuaGiftsProto.GuaGiftsRelationTemp.newBuilder();
                    relationTemp.setTargetUserId(targetRelation.getTargetUserId());
                    relationTemp.setUserBaseInfo(respMsg.getUserRelation().getUserBaseInfo());
                    relationTemp.setSendGiftCount(targetRelation.getSendCount());
                    relationTemp.setGetGiftCount(targetRelation.getGetCount());
                    relationTemp.setTotalGiftCount(respMsg.getUserRelation().getTotalGiftCount());
                    respMsg.setUserRelation(relationTemp);
                }
            }


            player.sendPacket(ClientProtocol.U_GUAGIFTS_SEARCH_USER, respMsg);

            return 0;

        } else {

            GuaGiftsProto.GuaGiftsSearchUserReqMsg.Builder builder = GuaGiftsProto.GuaGiftsSearchUserReqMsg.newBuilder();
            builder.setActivityId(GuaGiftsMgr.getConfig().getActivityId());
            builder.setTargetAliasId(reqMsg.getTargetAliasId());
            builder.setServerId(reqMsg.getServerId());
            builder.setGiftType(giftType);

            GuaGiftsProto.GuaGiftsSearchUserRespMsg.Builder resp = GuaGiftsProto.GuaGiftsSearchUserRespMsg.newBuilder();

            CompletableFuture<SyncResponse> future = GamePlayerMgr.sendToGameServer(reqMsg.getServerId(), GameProtocol.S_GUAGIFTS_SEARCH_USER, player.getUserId(), builder, resp);
            future.thenAccept((SyncResponse syncResponse) -> {
                if (syncResponse.getErrorCode() != 0) {
                    resp.setRet(syncResponse.getErrorCode());
                }
                resp.setActivityId(GuaGiftsMgr.getConfig().getActivityId());
                resp.setGiftType(giftType);
                if (giftType == 1){
                    UserGuaNobleRelationData targetRelation = getNobleTargetRelation(resp.getUserRelation().getTargetUserId());
                    if (targetRelation != null) {
                        GuaGiftsProto.GuaGiftsRelationTemp.Builder relationTemp = GuaGiftsProto.GuaGiftsRelationTemp.newBuilder();
                        relationTemp.setTargetUserId(targetRelation.getTargetUserId());
                        relationTemp.setUserBaseInfo(resp.getUserRelation().getUserBaseInfo());
                        relationTemp.setSendGiftCount(targetRelation.getSendCount());
                        relationTemp.setGetGiftCount(targetRelation.getGetCount());
                        relationTemp.setTotalGiftCount(resp.getUserRelation().getTotalGiftCount());
                        resp.setUserRelation(relationTemp);
                    }
                }else{
                    UserGuaRelationData targetRelation = getTargetRelation(resp.getUserRelation().getTargetUserId());
                    if (targetRelation != null) {
                        GuaGiftsProto.GuaGiftsRelationTemp.Builder relationTemp = GuaGiftsProto.GuaGiftsRelationTemp.newBuilder();
                        relationTemp.setTargetUserId(targetRelation.getTargetUserId());
                        relationTemp.setUserBaseInfo(resp.getUserRelation().getUserBaseInfo());
                        relationTemp.setSendGiftCount(targetRelation.getSendCount());
                        relationTemp.setGetGiftCount(targetRelation.getGetCount());
                        relationTemp.setTotalGiftCount(resp.getUserRelation().getTotalGiftCount());
                        resp.setUserRelation(relationTemp);
                    }
                }

                player.sendPacket(ClientProtocol.U_GUAGIFTS_SEARCH_USER, resp);
            });

            return -1;
        }
    }

    public int getGiftList(int giftType) {
        int ret = checkActivityShowRet();
        if (ret != 0) {
            return ret;
        }

        Map<Long, Set<Long>> needUserInfoFromOtherServer = new HashMap<>();
        Map<Long, UserGuaGiftData> waitUserInfoGiftMap = new HashMap<>();

        GuaGiftsProto.GuaGiftsGiftListIdxRespMsg.Builder respMsg = GuaGiftsProto.GuaGiftsGiftListIdxRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setActivityId(GuaGiftsMgr.getConfig().getActivityId());
        respMsg.setGiftType(giftType);

        if (giftType == 1){
            synchronized (userNobleGiftList){
                for (UserGuaGiftData userGuaGiftData : userNobleGiftList) {
                    long targetUserId = userGuaGiftData.getTargetUserId();

                    GuaGiftsProto.GuaGiftsGiftTemp.Builder builder = GuaGiftsProto.GuaGiftsGiftTemp.newBuilder();
                    builder.setTargetUserId(userGuaGiftData.getTargetUserId());
                    builder.setGiftTime(userGuaGiftData.getGiftTime());
                    builder.setGiftId(userGuaGiftData.getGoodsId());
                    builder.setGiftCount(userGuaGiftData.getGoodsCount());
                    builder.setContent(userGuaGiftData.getContent());

                    UserBaseInfo userBaseInfo = UserMgr.getUserBaseInfo(targetUserId, GameServer.getInstance().getServerId());
                    if (userBaseInfo == null) {
                        //本服没有去商会找一下
                        CrossUnionMember unionMember = CrossUnionMgr.getUnionMember(targetUserId);
                        if (unionMember != null) {
                            userBaseInfo = unionMember.getUserBaseInfo();
                        }
                    }

                    if (userBaseInfo != null) {
                        builder.setUserBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
                    } else {
                        long targetServerId = RelativesMgr.getUserServerId(targetUserId);
                        Set<Long> userIds = needUserInfoFromOtherServer.get(targetServerId);
                        if (userIds == null) {
                            userIds = new HashSet<>();
                            needUserInfoFromOtherServer.put(targetServerId, userIds);
                        }
                        userIds.add(targetUserId);

                        waitUserInfoGiftMap.put(targetUserId, userGuaGiftData);
                    }


                    respMsg.addGiftIdx(builder);
                }
            }
        }else if (giftType == 2){
            synchronized (userGuaGiftList){
                for (UserGuaGiftData userGuaGiftData : userGuaGiftList) {
                    long targetUserId = userGuaGiftData.getTargetUserId();

                    GuaGiftsProto.GuaGiftsGiftTemp.Builder builder = GuaGiftsProto.GuaGiftsGiftTemp.newBuilder();
                    builder.setTargetUserId(userGuaGiftData.getTargetUserId());
                    builder.setGiftTime(userGuaGiftData.getGiftTime());
                    builder.setGiftId(userGuaGiftData.getGoodsId());
                    builder.setGiftCount(userGuaGiftData.getGoodsCount());
                    builder.setContent(userGuaGiftData.getContent());

                    UserBaseInfo userBaseInfo = UserMgr.getUserBaseInfo(targetUserId, GameServer.getInstance().getServerId());
                    if (userBaseInfo == null) {
                        //本服没有去商会找一下
                        CrossUnionMember unionMember = CrossUnionMgr.getUnionMember(targetUserId);
                        if (unionMember != null) {
                            userBaseInfo = unionMember.getUserBaseInfo();
                        }
                    }

                    if (userBaseInfo != null) {
                        builder.setUserBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
                    } else {
                        long targetServerId = RelativesMgr.getUserServerId(targetUserId);
                        Set<Long> userIds = needUserInfoFromOtherServer.get(targetServerId);
                        if (userIds == null) {
                            userIds = new HashSet<>();
                            needUserInfoFromOtherServer.put(targetServerId, userIds);
                        }
                        userIds.add(targetUserId);

                        waitUserInfoGiftMap.put(targetUserId, userGuaGiftData);
                    }


                    respMsg.addGiftIdx(builder);
                }
            }
        }

        player.sendPacket(ClientProtocol.U_GUAGIFTS_GIFT_LIST_IDX, respMsg);

        //先发所有礼物的索引,如果有取不到userInfo的,取其他服取回来后,用22619发给客户端做填充.

        for (Map.Entry<Long, Set<Long>> entry : needUserInfoFromOtherServer.entrySet()) {
            Long serverId = entry.getKey();
            Set<Long> userIds = entry.getValue();

            QixiProto.QixiGetUserInfoReqMsg.Builder reqMsg = QixiProto.QixiGetUserInfoReqMsg.newBuilder();
            reqMsg.setActivityId(GuaGiftsMgr.getConfig().getActivityId());
            reqMsg.addAllTargetUserId(userIds);
            reqMsg.setReqProtocolType(GameProtocol.S_GUAGIFTS_GIFT_LIST);

            QixiProto.QixiGetUserInfoRespMsg.Builder resp = QixiProto.QixiGetUserInfoRespMsg.newBuilder();

            CompletableFuture<SyncResponse> future = GamePlayerMgr.sendToGameServer(serverId, GameProtocol.S_QIXI_GET_USER_INFO, player.getUserId(), reqMsg, resp);
            future.thenAccept((SyncResponse syncResponse) -> {
                if (syncResponse.getErrorCode() != 0) {
                    return;
                }
                if (resp.getReqProtocolType() != GameProtocol.S_GUAGIFTS_GIFT_LIST) {
                    return;
                }
                GuaGiftsProto.GuaGiftsGiftListRespMsg.Builder giftMsg = GuaGiftsProto.GuaGiftsGiftListRespMsg.newBuilder();
                giftMsg.setActivityId(GuaGiftsMgr.getConfig().getActivityId());
                giftMsg.setGiftType(giftType);
                for (QixiProto.QixiRelationTemp temp : resp.getRelationListList()) {
                    long targetUserId = temp.getTargetUserId();
                    PlayerProto.PlayerBaseTempMsg userBaseInfo = temp.getUserBaseInfo();

                    if (giftType == 1){
                        for (UserGuaGiftData userGuaGiftData : this.userNobleGiftList) {
                            if (userGuaGiftData.getTargetUserId() == targetUserId) {
                                GuaGiftsProto.GuaGiftsGiftTemp.Builder builder = GuaGiftsProto.GuaGiftsGiftTemp.newBuilder();
                                builder.setTargetUserId(userGuaGiftData.getTargetUserId());
                                builder.setGiftTime(userGuaGiftData.getGiftTime());
                                builder.setGiftId(userGuaGiftData.getGoodsId());
                                builder.setGiftCount(userGuaGiftData.getGoodsCount());
                                builder.setContent(userGuaGiftData.getContent());
                                builder.setUserBaseInfo(userBaseInfo);

                                giftMsg.addGiftList(builder);
                            }
                        }
                    } else if (giftType == 2){
                        for (UserGuaGiftData userGuaGiftData : this.userGuaGiftList) {
                            if (userGuaGiftData.getTargetUserId() == targetUserId) {
                                GuaGiftsProto.GuaGiftsGiftTemp.Builder builder = GuaGiftsProto.GuaGiftsGiftTemp.newBuilder();
                                builder.setTargetUserId(userGuaGiftData.getTargetUserId());
                                builder.setGiftTime(userGuaGiftData.getGiftTime());
                                builder.setGiftId(userGuaGiftData.getGoodsId());
                                builder.setGiftCount(userGuaGiftData.getGoodsCount());
                                builder.setContent(userGuaGiftData.getContent());
                                builder.setUserBaseInfo(userBaseInfo);

                                giftMsg.addGiftList(builder);
                            }
                        }
                    }

                    UserGuaGiftData userGuaGiftData = waitUserInfoGiftMap.get(targetUserId);
//                    if (userGuaGiftData != null) {
//                        GuaGiftsProto.GuaGiftsGiftTemp.Builder giftTemp = GuaGiftsProto.GuaGiftsGiftTemp.newBuilder();
//                        giftTemp.setTargetUserId(userGuaGiftData.getTargetUserId());
//                        giftTemp.setGiftTime(userGuaGiftData.getGiftTime());
//                        giftTemp.setGiftId(userGuaGiftData.getGoodsId());
//                        giftTemp.setGiftCount(userGuaGiftData.getGoodsCount());
//                        giftTemp.setContent(userGuaGiftData.getContent());
//                        giftTemp.setUserBaseInfo(temp.getUserBaseInfo());
//
//                        giftMsg.addGiftList(giftTemp);
//                    }
                }

                player.sendPacket(ClientProtocol.U_GUAGIFTS_GIFT_LIST, giftMsg);

            });
        }

        return 0;
    }

    public int receiveGift() {
        int ret = checkActivityShowRet();
        if (ret != 0) {
            return ret;
        }

        if (userNobleGiftList.isEmpty()) {
            return GameErrorCode.E_GUAGIFTS_GIFT_EMPTY;
        }

        Property totalReward = new Property();
        Property showReward = new Property(); //新需求,要求显示收了多少花

        synchronized (userNobleGiftList) {
            for (UserGuaGiftData userGuaGiftData : userNobleGiftList) {
                userGuaGiftData.setStatus(1);
                needUpdateGiftList.add(userGuaGiftData);

                GoodsInfo giftInfo = GoodsMgr.getGoodsById(userGuaGiftData.getGoodsId());
                if (giftInfo == null) {
                    continue;
                }

                Property giftReward = GuaGiftsMgr.getGiftReward(giftInfo, userGuaGiftData.getGoodsCount());
                if (!giftReward.isNothing()) {
                    totalReward.addProperty(giftReward);
                }
                //需求跟七夕不一样,这里不塞进去了。
//                showReward.addProperty(new Property(giftInfo.getGoodsId(), userGuaGiftData.getGoodsCount()));
            }

            userNobleGiftList.clear();
        }

        if (!totalReward.isNothing()) {
            player.getModule(CurrencyModule.class).addCurrency(totalReward, eLogMoneyType.GuaGiftsActivity, eLogMoneyType.GuaGiftsActivityGiftReward);
        }

        showReward.addProperty(totalReward);

        GuaGiftsProto.GuaGiftsReceiveGiftRespMsg.Builder respMsg = GuaGiftsProto.GuaGiftsReceiveGiftRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setActivityId(GuaGiftsMgr.getConfig().getActivityId());
        respMsg.setReward(PropertyHelper.parsePropertyToString(showReward));

        player.sendPacket(ClientProtocol.U_GUAGIFTS_RECEIVE_GIFT, respMsg);

        syncUserData();

        return 0;
    }

    public synchronized long getGiftMostUserId(int giftType) {
        if (giftType == 1){
            return GuaGiftsMgr.getNobleGiftMostUserIdByRelationMap(userNobleRelationMap);
        }else{
            return GuaGiftsMgr.getGiftMostUserIdByRelationMap(userRelationMap);
        }
    }

    public void getBroadcastRewardCrossBack(GuaGiftsProto.CrossGetBroadcastRewardRespMsg resultMsg) {
        GuaGiftsProto.GuaGiftsReceiveBroadcastRewardRespMsg.Builder clientMsg = GuaGiftsProto.GuaGiftsReceiveBroadcastRewardRespMsg.newBuilder();
        clientMsg.setRet(0);
        if (resultMsg.getRet() != 0) {
            clientMsg.setRet(resultMsg.getRet());
            player.sendPacket(ClientProtocol.U_GUAGIFTS_RECEIVE_BROADCAST_REWARD, clientMsg);
            return;
        }

        if (userData.wasGetBroadcast(resultMsg.getBroadcastId())) {
            clientMsg.setRet(GameErrorCode.E_GUAGIFTS_BROADCAST_WAS_GET);
            player.sendPacket(ClientProtocol.U_GUAGIFTS_RECEIVE_BROADCAST_REWARD, clientMsg);
            return;
        }

        userData.addBroadcastId(resultMsg.getBroadcastId());

        Property broadcastReward = GuaGiftsMgr.getConfig().getBroadcastReward();
        player.getModule(CurrencyModule.class).addCurrency(broadcastReward, eLogMoneyType.GuaGiftsActivity, eLogMoneyType.GuaGiftsActivityBroadcastReward);
        String rewardString = PropertyHelper.parsePropertyToString(broadcastReward);
        clientMsg.setBroadcastId(resultMsg.getBroadcastId());
        clientMsg.setReward(rewardString);

        AutoLogMgr.add(new LogGuaGiftsReceiveBroadcast(GuaGiftsMgr.getConfig().getActivityId(), player.getUserId(), resultMsg.getBroadcastId(), rewardString));

        player.sendPacket(ClientProtocol.U_GUAGIFTS_RECEIVE_BROADCAST_REWARD, clientMsg);

    }

    public int receiveBroadcastReward(long broadcastId) {
        int ret = checkActivityShowRet();
        if (ret != 0) {
            return ret;
        }

        if (userData.wasGetBroadcast(broadcastId)) {
            return GameErrorCode.E_GUAGIFTS_BROADCAST_WAS_GET;
        }

        if (!userData.wasWatchBroadcast(broadcastId)) {
            return GameErrorCode.E_GUAGIFTS_BROADCAST_NOT_WATCH;
        }

        GuaGiftsProto.CrossGetBroadcastRewardReqMsg.Builder crossMsg = GuaGiftsProto.CrossGetBroadcastRewardReqMsg.newBuilder();
        crossMsg.setActivityId(GuaGiftsMgr.getConfig().getActivityId());
        crossMsg.setBroadcastId(broadcastId);

        player.sendPacket(CrossProtocol.C_GUAGIFTS_GET_GIFT_BROADCAST_REWARD, crossMsg);

        return -1;
    }

    public void broadcastCrossBack(GuaGiftsProto.CrossGuaGiftsBroadcastBackMsg resultMsg) {
        int ret = checkActivityRet();
        if (ret != 0) {
            return;
        }
        removeOverBroadcastId();
        for (GuaGiftsProto.GuaGiftsGiftBroadcastMsg broadcastMsg : resultMsg.getBroadcastListList()) {
            if (!userData.getWatchBroadcastList().contains(broadcastMsg.getBroadcastId())) {
                player.sendPacket(ClientProtocol.U_GUAGIFTS_GIFTS_BROADCAST, broadcastMsg.toBuilder());
            }
            userData.addWatchBroadcastId(broadcastMsg.getBroadcastId());
        }
    }

    public boolean canChargeSucceed(int mallId) {
        int ret = checkActivityRet();
        if (ret != 0) {
            return false;
        }

        return true;
    }

    public void removeOverBroadcastId() {
        int ret = checkActivityShowRet();
        if (ret != 0) {
            return;
        }
        long currentTime = DateHelper.getCurrentTime();
        if (currentTime - userData.getLastWatchTime() > GuaGiftsMgr.getConfig().getBROADCASTING_TIME() * DateHelper.MINUTE_MILLIONS + 1 * DateHelper.MINUTE_MILLIONS) {
            //超过有效时间了。所以可以清掉。因为都领不了了。
            userData.getWatchBroadcastList().clear();
            userData.getGetBroadcastList().clear();
            userData.setUpdateOption();
        }
    }

    public UserGuaData getUserData() {
        return userData;
    }

    public void syncAllOpenServerList() {
        int ret = checkActivityShowRet();
        if (ret != 0) {
            return;
        }
        GuaGiftsProto.GuaGiftsAllOpenServerListSyncMsg.Builder allOpenServerListMsg = GuaGiftsMgr.getAllOpenServerListMsg();
        player.sendPacket(ClientProtocol.U_QIXI_ALL_OPEN_SERVER_LIST, allOpenServerListMsg);
    }
}
